package com.order.service.impl;

import java.util.List;

import javax.annotation.Resource;

import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.order.dao.ICustomerDao;
import com.order.dao.IUserDao;
import com.order.domain.User;
import com.order.service.IUserService;

/**
 * 用户的业务层实现类
 * 
 * @author zhy
 *
 */
@Service("userService")
@Transactional(readOnly = true, propagation = Propagation.SUPPORTS)
public class UserServiceImpl implements IUserService {

	@Resource(name = "userDao")
	private IUserDao userDao;
	
	@Resource(name = "customerDao")
	private ICustomerDao customerDao;

	@Override
	public List<User> findAllUser(DetachedCriteria uCriteria) {
		return userDao.findAll(uCriteria);
	}

	@Override
	@Transactional(readOnly = false, propagation = Propagation.REQUIRED)
	public void saveUser(User user) {
		userDao.save(user);
	}

	@Override
	@Transactional(readOnly = false, propagation = Propagation.REQUIRED)
	public void removeUser(Integer userId) {
		userDao.delete(userId);
	}

	@Override
	public User findUserById(Integer userId) {
		return userDao.findById(userId);
	}

	@Override
	@Transactional(readOnly = false, propagation = Propagation.REQUIRED)
	public void updateUser(User user) {
		userDao.update(user);
	}

	@Override
	public User findByUserNameAndPwd(String userName, String password) {

		return userDao.findByUserNameAndPwd(userName, password);
	}

	@Override
	@Transactional(readOnly = false, propagation = Propagation.REQUIRED)
	public void pwdUpdate(User user) {
		userDao.update(user);
	}

	/**
	 * 更新学生数量
	 */
	@Override
	@Transactional(readOnly = false, propagation = Propagation.REQUIRED)
	public void updateStudentNum(DetachedCriteria dCriteria , Integer userId) {
		dCriteria.add(Restrictions.eq("affiliatedTeacher.userId" , userId));
		dCriteria.setProjection(Projections.rowCount());
		Integer studentNum = customerDao.findStudentNum(dCriteria);
		
		userDao.update(userId , studentNum);
		
	}

}
